import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 特殊标记,用于标记token过期后禁止请求后端api
var interruptRequest = false

// create an axios instance
const service = axios.create({
  // baseURL: `${process.env.VUE_APP_BASE_API}/`, // url = base url + request url
  baseURL: window.EnvConfig.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 40000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }

    if (interruptRequest) {
      return Promise.reject({
        response: { status: 40001 } // 返回特殊状态码
      })
    }

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response拦截器
service.interceptors.response.use(
  response => {
    let data
    // IE9时response.data是undefined，因此需要使用response.request.responseText(Stringify后的字符串)
    if (response.data === undefined) {
      data = JSON.parse(response.request.responseText)
    } else {
      data = response.data
    }
    // console.log(data)
    // 二进制流文件 - 单独对blob的处理
    if (response.config.responseType === 'blob') {
      return response;
    }
    if (data.code !== 200) {
      Message({
        message: data.msg || '提示',
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(data)
    } else {
      if (data.code === 200 && data.msg) {
        Message({
          message: data.msg || '提示',
          type: 'success',
          duration: 3 * 1000
        })
      }
    }

    return data
  },
  err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误'
          break
        case 401:
          if (err.response.data.code === 401) {
            err.message = err.response.data.msg;
          } else {
            interruptRequest = true
            err.message = '登录失效，请重新登录'
            MessageBox.confirm('您的登录信息已失效，请重新登录', '登录信息失效提醒', {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning',
              center: true
            }).then(() => {
              interruptRequest = false
              store.dispatch('user/resetToken').then(() => {
                location.reload()
              })
            }).catch(action => {
              interruptRequest = false
            });
          }
          break
        case 40001:
          err.message = '登录失效，请重新登录'
          break
        case 403:
          err.message = '禁止访问'
          break
        case 404:
          err.message = `请求地址出错: ${err.response.config.url}`
          break
        case 408:
          err.message = '请求超时'
          break
        case 500:
          err.message = '未知错误'
          break
        case 501:
          err.message = '服务未实现'
          break
        case 502:
          err.message = '网关错误'
          break
        case 503:
          err.message = '服务不可用'
          break
        case 504:
          err.message = '网关超时'
          break
        case 505:
          err.message = 'HTTP版本不受支持'
          break
        default:
          err.message = '未知错误'
          break
      }
    }

    var returnMsg = {
      message: err.message || '未知错误',
      type: 'error',
      duration: 3 * 1000
    }
    Message(returnMsg);
    return Promise.reject(returnMsg) // 返回接口返回的错误信息
  }
)

export default service
